package com.gitee.faster.webdav.kernel.protocol.filter;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.swing.DesktopUtil;
import com.gitee.faster.webdav.common.constant.Constants;
import com.gitee.faster.webdav.common.helper.JsonHelper;
import com.gitee.faster.webdav.common.structure.SystemSnapshot;
import com.gitee.faster.webdav.kernel.event.EventPublisher;
import com.gitee.faster.webdav.kernel.event.NotificationEvent;
import com.gitee.faster.webdav.kernel.event.ShutdownEvent;
import com.gitee.faster.webdav.kernel.protocol.HttpExchange;
import lombok.Data;
import lombok.experimental.Accessors;
import org.smartboot.http.common.enums.HttpStatus;

import java.awt.*;
import java.io.File;

/**
 * 系统 API 接口拦截器
 *
 * @author hongda.li
 */
public class HttpFilterSystemApi implements HttpFilter {

    private static final String PARAM_NAME_FILE_PATH = "filePath";

    @Override
    public boolean doNext(HttpExchange httpExchange) {
        if (!httpExchange.getPath().startsWith(Constants.API_PATH)) {
            return true;
        }

        switch (httpExchange.getMethodEnum()) {
            case GET:
                // 获取配置
                httpExchange.writeJsonResult(SystemSnapshot.snapshot());
                break;
            case DELETE:
                // 关闭系统
                EventPublisher.getInstance().publishEvent(new ShutdownEvent());
                break;
            case POST:
                // 打开日志
                this.openLogFile(httpExchange);
                break;
            case PUT:
                // 更新配置
                this.updateConfig(httpExchange);
                break;
            default:
                break;
        }

        httpExchange.setHttpStatus(HttpStatus.OK);

        return false;
    }

    private void updateConfig(HttpExchange httpExchange) {

    }

    private void openLogFile(HttpExchange httpExchange) {
        LogRequest request = JsonHelper.fromJson(httpExchange.readFromInputStream(), LogRequest.class);
        if (request == null) {
            return;
        }

        File file = new File(request.path);

        // 打开日志文件或删除
        if (request.status && FileUtil.exist(file)) {
            DesktopUtil.open(file);
        } else {
            FileUtil.del(file);

            NotificationEvent notificationEvent = new NotificationEvent();
            notificationEvent.setTitle("已删除日志文件");
            notificationEvent.setMessage(request.path);
            notificationEvent.setMessageType(TrayIcon.MessageType.INFO);
            EventPublisher.getInstance().publishEvent(notificationEvent);
        }
    }

    @Data
    @Accessors(chain = true)
    private static final class LogRequest {
        /**
         * 日志存储路径
         */
        private String path;

        /**
         * 操作状态 : true 打开 / false 删除
         */
        private boolean status;
    }
}
